package com.demo.crm.springboot3security.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.demo.crm.springboot3security.entity.Permission;
import com.demo.crm.springboot3security.mapper.PermissionMapper;
import com.demo.crm.springboot3security.service.PermissionService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public Permission findByName(String name) {
        return permissionMapper.findByName(name);
    }

    @Override
    public Permission findByPermissionKey(String permissionKey) {
        return permissionMapper.findByPermissionKey(permissionKey);
    }

    @Override
    @Transactional
    public Permission save(Permission permission) {
        if (permission.getId() == null) {
            permissionMapper.insert(permission);
        } else {
            permissionMapper.update(permission);
        }
        return permission;
    }

    @Override
    @Transactional
    public void delete(Long id) {
        permissionMapper.deleteById(id);
    }

    @Override
    public Permission findById(Long id) {
        return permissionMapper.selectOneById(id);
    }

    @Override
    public List<Permission> findAll() {
        return permissionMapper.selectAll();
    }

    @Override
    public Page<Permission> findByPage(int pageNumber, int pageSize) {
        return permissionMapper.paginate(pageNumber, pageSize, QueryWrapper.create());
    }

    @Override
    public boolean existsByName(String name) {
        QueryWrapper query = QueryWrapper.create().where("name = ?", name);
        return permissionMapper.selectCountByQuery(query) > 0;
    }

    @Override
    public boolean existsByPermissionKey(String permissionKey) {
        QueryWrapper query = QueryWrapper.create().where("permission_key = ?", permissionKey);
        return permissionMapper.selectCountByQuery(query) > 0;
    }
} 